<?php
function Google($args, $ctimer){
	$fp = @fsockopen("www.google.com", 80, $errno, $errstr, $ctimer);
	if (!$fp){
		echo "$errstr ($errno)\n";
	}else {
		$args = str_replace(' ','+',str_replace(chr(13), '', str_replace(chr(10), '', $args)));
		$out = "GET /search?q=".$args." HTTP/1.1\r\n";
		$out .= "Host: www.google.com\r\n";
		$out .= "User-Agent: Jacqli/0.3 jacqli.mir@gmail.com\r\n";
		$out .= "Connection: Close\r\n\r\n";
		fwrite($fp, $out);
		$results = "";
		while (!feof($fp)) {
			$results .= fread($fp, 1000);
		}
		fclose($fp);
		
		echo "{Google result} $results\n";

		$results = str_replace(array('<em>','</em>','<b>','</b>'),'',$results);
		if(preg_match('@<h3 class="r"><a href="[^"]*"[^<]*@i',$results,$matches)){ //TODO: fix all these regexes so we get title & text
			$matches[0] = str_ireplace('<h3 class="r">','',$matches[0]);
			echo "matches:$matches[0]\n";
			if(preg_match('@/url\?q=.*&amp;sa=U&amp;ei=@i',$matches[0],$url)){
				if(preg_match('@>.*@i',$matches[0],$title)){
					$url = str_replace('/url?q=','',html_entity_decode(str_replace('&amp;sa=U&amp;ei=','',$url[0]),ENT_QUOTES,"UTF-8"));
					echo "URL:$url\n";
					$title = str_replace(array(chr(41),'"','>','class=l'),'',html_entity_decode(str_replace('>','',$title[0]),ENT_QUOTES,"UTF-8"));					
					return "$title | $url";
				}else{
					echo "no title found\n"; 
					return "No match found.";
				}
			}else{
				echo "no url found\n"; 
				return "No match found.";
			}
		}else{
			echo "no match at all\n"; 
			return "No match found.";
		}
	}
	flush();
}
?>